package com.nttdata.ta.todo.controller;

import com.nttdata.ta.common.security.JwtTokenProvider;
import com.nttdata.ta.todo.model.TodoItem;
import com.nttdata.ta.todo.repository.TodoItemRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/api/todos")
public class TodoItemController {

    @Autowired
    private TodoItemRepository repository;

    @Autowired
    private JwtTokenProvider jwtTokenProvider;

    @GetMapping
    public ResponseEntity<List<TodoItem>> getAllTodos(
            @RequestHeader("Authorization") String token) {
        String username = jwtTokenProvider.getUsername(token.substring(7));
        Long userId = getUserIdFromUsername(username); // 需要实现用户服务调用
        return ResponseEntity.ok(repository.findByUserId(userId));
    }

    @PostMapping
    public ResponseEntity<TodoItem> addTodo(
            @RequestBody TodoItem todoItem,
            @RequestHeader("Authorization") String token) {
        String username = jwtTokenProvider.getUsername(token.substring(7));
        Long userId = getUserIdFromUsername(username);
        todoItem.setUserId(userId);
        return ResponseEntity.ok(repository.save(todoItem));
    }

    @PutMapping("/{id}")
    public ResponseEntity<TodoItem> updateTodo(
            @PathVariable Long id,
            @RequestBody TodoItem todoItem,
            @RequestHeader("Authorization") String token) {
        String username = jwtTokenProvider.getUsername(token.substring(7));
        Long userId = getUserIdFromUsername(username);

        return repository.findById(id)
                .map(existingItem -> {
                    if (!existingItem.getUserId().equals(userId)) {
                        return ResponseEntity.status(403).build();
                    }
                    todoItem.setId(id);
                    todoItem.setUserId(userId);
                    return ResponseEntity.ok(repository.save(todoItem));
                })
                .orElseGet(() -> ResponseEntity.notFound().build());
    }

    @DeleteMapping("/{id}")
    public ResponseEntity<Void> deleteTodo(
            @PathVariable Long id,
            @RequestHeader("Authorization") String token) {
        String username = jwtTokenProvider.getUsername(token.substring(7));
        Long userId = getUserIdFromUsername(username);

        return repository.findById(id)
                .map(item -> {
                    if (!item.getUserId().equals(userId)) {
                        return ResponseEntity.status(403).build();
                    }
                    repository.deleteById(id);
                    return ResponseEntity.noContent().build();
                })
                .orElseGet(() -> ResponseEntity.notFound().build());
    }

    private Long getUserIdFromUsername(String username) {
        // 这里应该调用用户服务获取用户ID
        // 暂时返回1L作为示例
        return 1L;
    }
}